package redis

import "github.com/go-redis/redis/v8"

type Script struct {
	rdsIns *RedisIns
	script *redis.Script
}

func (s *Script) Run(keys []string, params ...interface{}) (interface{}, error) {
	return s.script.Run(s.rdsIns.ctx, s.rdsIns.ins, keys, params...).Result()
}

type InnerScripts struct {
	SetTTL  *Script
	SetNotE *Script
}

func (r *RedisIns) initInnerScript() {
	r.scripts = new(InnerScripts)
	r.scripts.SetTTL, _ = r.loadScript(`
		local ttl = ARGV[#ARGV]
		ARGV[#ARGV] = nil
		if redis.call('EXISTS', KEYS[1]) ~= 1 then
			return -1
		end
		local res = redis.call('SET', KEYS[1], unpack(ARGV))
		if not res then
			return 2
		end
		redis.call('EXPIRE', KEYS[1], ttl)
		return 1
		`)
	r.scripts.SetNotE, _ = r.loadScript(`
		if redis.call('EXISTS', KEYS[1]) == 1 then
			return -1
		end
		local res = redis.call('SET', KEYS[1], unpack(ARGV[1]))
		if not res then
			return 2
		end
		return 1
	`)
}
